package top.kaoshanji.p1ch05a;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import top.kaoshanji.p1ch04a.Dish;

import java.util.Arrays;
import java.util.List;
import java.util.Optional;

/**
 * author kaoshanji
 * ^_^
 * create time 2025/2/11 11:18
 */
public class Finding {

    private static final Logger logger = LogManager.getLogger(Finding.class);

    public static void main(String[] args) {

        // 代码清单-p1ch05a-95页a：检查谓词是否至少匹配一个元素
        logger.info("...检查谓词是否至少匹配一个元素...");
        if (isVegetarianFriendlyMenu()) {
            System.out.println("Vegetarian friendly");
        }


        // 代码清单-p1ch05a-96页a：检查谓词是否匹配所有元素
        logger.info("...检查谓词是否匹配所有元素...");
        System.out.println(isHealthyMenu());
        System.out.println(isHealthyMenu2());


        // 代码清单-p1ch05a-96页b：查找元素
        logger.info("...查找元素...");
        Optional<Dish> dish = findVegetarianDish();
        dish.ifPresent(d -> System.out.println(d.getName()));


        // 代码清单-p1ch05a-97页a：查找第一个元素
        logger.info("...查找第一个元素...");
        List<Integer> someNumbers = Arrays.asList(1, 2, 3, 4, 5);
        Optional<Integer> firstSquareDivisibleByThree = someNumbers.stream()
                .map(n -> n * n)
                .filter(n -> n % 3 == 0)
                .findFirst();
        firstSquareDivisibleByThree.ifPresent(System.out::println);

    }


    private static boolean isVegetarianFriendlyMenu() {
        return Dish.menu.stream().anyMatch(Dish::isVegetarian);
    }

    private static boolean isHealthyMenu() {
        return Dish.menu.stream().allMatch(d -> d.getCalories() < 1000);
    }

    private static boolean isHealthyMenu2() {
        return Dish.menu.stream().noneMatch(d -> d.getCalories() >= 1000);
    }

    private static Optional<Dish> findVegetarianDish() {
        return Dish.menu.stream().filter(Dish::isVegetarian).findAny();
    }


}
